package com.controller;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.Address;
import com.entity.view.AddressView;
import com.service.AddressService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 地址
 * 后端接口
 * @author 
 * @email 
 * @date 2023-12-12 13:37:41
 */
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,Address address,
		HttpServletRequest request){
            address.setUserId((Integer)request.getSession().getAttribute("userId"));
        EntityWrapper<Address> ew = new EntityWrapper<Address>();

		PageUtils page = addressService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, address), params), params));

        return R.ok().put("data", page);
    }
    
    /**
     * 前端列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,Address address,
		HttpServletRequest request){
    		address.setUserId((Integer) request.getSession().getAttribute("userId"));
        EntityWrapper<Address> ew = new EntityWrapper<Address>();

		PageUtils page = addressService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, address), params), params));
        return R.ok().put("data", page);
    }

	/**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( Address address){
       	EntityWrapper<Address> ew = new EntityWrapper<Address>();
      	ew.allEq(MPUtil.allEQMapPre( address, "address")); 
        return R.ok().put("data", addressService.selectListView(ew));
    }

	 /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(Address address){
        EntityWrapper< Address> ew = new EntityWrapper< Address>();
 		ew.allEq(MPUtil.allEQMapPre( address, "address")); 
		AddressView addressView =  addressService.selectView(ew);
		return R.ok("查询地址成功").put("data", addressView);
    }
	
    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
        Address address = addressService.selectById(id);
        return R.ok().put("data", address);
    }

    /**
     * 前端详情
     */
	@IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Integer id){
        Address address = addressService.selectById(id);
        return R.ok().put("data", address);
    }
    



    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody Address address, HttpServletRequest request){
    	//ValidatorUtils.validateEntity(address);
    	address.setUserId((Integer) request.getSession().getAttribute("userId"));
		Integer userId = (Integer)request.getSession().getAttribute("userId");
    	if(address.isDefault()) {
    		addressService.updateForSet("isdefault=false", new EntityWrapper<Address>().eq("userId", userId));
    	}
    	address.setUserId(userId);
        addressService.insert(address);
        return R.ok();
    }
    
    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody Address address, HttpServletRequest request){
    	//ValidatorUtils.validateEntity(address);
    	address.setUserId((Integer)request.getSession().getAttribute("userId"));
        Integer userId = (Integer)request.getSession().getAttribute("userId");
    	if(address.isDefault()) {
    		addressService.updateForSet("isdefault=false", new EntityWrapper<Address>().eq("userId", userId));
    	}
    	address.setUserId(userId);
        addressService.insert(address);
        return R.ok();
    }


     /**
     * 获取用户密保
     */
    @RequestMapping("/security")
    @IgnoreAuth
    public R security(@RequestParam String username){
        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("", username));
        return R.ok().put("data", address);
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    @IgnoreAuth
    public R update(@RequestBody Address address, HttpServletRequest request){
        //ValidatorUtils.validateEntity(address);
        if(address.isDefault()) {
    		addressService.updateForSet("isdefault=false", new EntityWrapper<Address>().eq("userId", request.getSession().getAttribute("userId")));
    	}
        addressService.updateById(address);//全部更新
        return R.ok();
    }



    
    /**
     * 获取默认地址
     */
    @RequestMapping("/default")
    public R defaultAddress(HttpServletRequest request){
    	Wrapper<Address> wrapper = new EntityWrapper<Address>().eq("isdefault", true).eq("userId", request.getSession().getAttribute("userId"));
        Address address = addressService.selectOne(wrapper);
        return R.ok().put("data", address);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        addressService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
    
	
	/**
     * 前端智能排序
     */
	@IgnoreAuth
    @RequestMapping("/autoSort")
    public R autoSort(@RequestParam Map<String, Object> params,Address address, HttpServletRequest request,String pre){
        EntityWrapper<Address> ew = new EntityWrapper<Address>();
        Map<String, Object> newMap = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
		Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = it.next();
			String key = entry.getKey();
			String newKey = entry.getKey();
			if (pre.endsWith(".")) {
				newMap.put(pre + newKey, entry.getValue());
			} else if (StringUtils.isEmpty(pre)) {
				newMap.put(newKey, entry.getValue());
			} else {
				newMap.put(pre + "." + newKey, entry.getValue());
			}
		}
		params.put("sort", "clicktime");
        params.put("order", "desc");
		PageUtils page = addressService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, address), params), params));
        return R.ok().put("data", page);
    }










}
